package com.ruoyi.salesInvoice.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.company.domain.Company;
import com.ruoyi.company.domain.CompanyOther;
import com.ruoyi.company.service.ICompanyInvoiceService;
import com.ruoyi.company.service.ICompanyOtherServer;
import com.ruoyi.company.service.ICompanyServer;
import com.ruoyi.company.utils.Util;
import com.ruoyi.expressdelivery.domain.ExpressDelivery;
import com.ruoyi.expressdelivery.mapper.ExpreeDeliveryMapper;
import com.ruoyi.expressdelivery.service.ExpressDeliveryService;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.sale.domain.SaleGoodsModel;
import com.ruoyi.sale.domain.SaleGoodsOrder;
import com.ruoyi.sale.service.IOutboundService;
import com.ruoyi.sale.service.ISaleGoodsService;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.salesInvoice.domain.SalesInvoiceModel;
import com.ruoyi.salesInvoice.domain.SalesInvoiceOrder;
import com.ruoyi.salesInvoice.mapper.SalesInvoiceMapper;
import com.ruoyi.salesInvoice.service.SalesInvoiceService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author jndj
 * @date 2022-06-17
 */
@RestController
@RequestMapping("/business/salesInvoice")
public class SalesInvoiceController extends BaseController {
    private String prefix = "salesInvoice";

    @Autowired
    private SalesInvoiceService invoiceService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private ISaleGoodsService saleGoodsService;

    @Autowired
    ISysDeptService iSysDeptService;

    @Autowired
    ICompanyInvoiceService iCompanyInvoiceService;

    @Autowired
    ISaleorderService iSaleorderService;

    @Autowired
    AuditService auditService;

    @Autowired
    ICompanyServer iCompanyServer;

    @Autowired
    ICompanyOtherServer iCompanyOtherServer;

    @Autowired
    IOutboundService iOutboundService;

    @Autowired
    ExpressDeliveryService expressDeliveryService;

    @Autowired
    SalesInvoiceMapper salesInvoiceMapper;

    @Autowired
    ExpreeDeliveryMapper expreeDeliveryMapper;
    @Autowired
    private SalesInvoiceService salesInvoiceService;

    @RequiresPermissions("business:salesInvoice:view")
    @GetMapping()
    public String order() {
        return prefix + "/list";
    }


    @PostMapping("/selectfpInformation")
    @ResponseBody
    public List<ExpressDelivery> selectFpInformation(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        String companyId = httpServletRequest.getParameter("companyId");
        List<ExpressDelivery> list = new ArrayList<>();
        try {
            list = expreeDeliveryMapper.selectfpInformation(companyId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @PostMapping("/updateWl")
    @ResponseBody
    public void update(HttpServletRequest request) {
        String saleordernum = request.getParameter("salesInvoiceNum");
        //  String fhnr = request.getParameter("fhnr");
        String phone = request.getParameter("phone");
        String shdz = request.getParameter("shdz");
        String fname = request.getParameter("name");

        String remarks = request.getParameter("remarks");

        try {
            expressDeliveryService.updateWlfp(phone, shdz, fname, saleordernum, remarks);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/selectinformation")
    @ResponseBody
    public Map<String, Object> selectinformation(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        Map<String, Object> resMap = new HashMap<>();
        String salesInvoiceNum = httpServletRequest.getParameter("salesInvoiceNum");
        List<SalesInvoiceOrder> list = new ArrayList<>();
        try {
            list = salesInvoiceMapper.selectinformation(salesInvoiceNum);
            if (list.size() != 0) {
                resMap.put("code", "0");
                resMap.put("result", list);
            } else {
                resMap.put("code", "-1");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resMap;
    }

    @Log(title = "审核销售订单", businessType = BusinessType.UPDATE)
    @GetMapping("/auditSale")
    @ResponseBody
    public AjaxResult auditSale(@RequestParam(value = "salesInvoiceId", required = false) Long salesInvoiceId,
                                @RequestParam(value = "invoiceStatus", required = false) String invoiceStatus) {
        SalesInvoiceOrder salesInvoiceOrder = new SalesInvoiceOrder();
        salesInvoiceOrder.setSalesInvoiceId(salesInvoiceId);
        salesInvoiceOrder.setInvoiceStatus(invoiceStatus);
        // return toAjax(salesInvoiceMapper.auditSale(salesInvoiceOrder));
        return toAjax(invoiceService.auditSale(salesInvoiceOrder));
    }


    @PostMapping("/selectSfInformation")
    @ResponseBody
    public Map<String, Object> selectSfInformation(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        Map<String, Object> resMap = new LinkedHashMap<>();
        String salesInvoiceNum = httpServletRequest.getParameter("salesInvoiceNum");
        List<ExpressDelivery> list = new ArrayList<>();
        try {
            list = salesInvoiceMapper.selectSfInformation(salesInvoiceNum);
            if (list.size() != 0) {
                resMap.put("result", list);
                resMap.put("code", "0");
            } else {
                resMap.put("code", "-1");
            }
        } catch (Exception e) {
            resMap.put("code", "-1");
            e.printStackTrace();
        }
        return resMap;
    }

    @PostMapping("/printsheet")
    @ResponseBody
    public Map<String, Object> postExpressDelivery(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        String msgData = httpServletRequest.getParameter("msgData");
        Map<String, Object> resMap = expressDeliveryService.PrintSheet(msgData);
        return resMap;
    }

    @PostMapping("/placeOrder")
    @ResponseBody
    public Map<String, Object> placeOrder(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        String saleorderNum = httpServletRequest.getParameter("salesInvoiceNum");
        String msgData = httpServletRequest.getParameter("msgData");
        String recipients = httpServletRequest.getParameter("recipients");//收件人电话号
        String sender = httpServletRequest.getParameter("sender");//寄件人手机号
        Map<String, Object> resMap = expressDeliveryService.placeOrderfp(msgData, saleorderNum, recipients, sender);
        return resMap;
    }

    /**
     * 查询销售发票订单列表
     */
    @RequiresPermissions("business:salesInvoice:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam(value = "invoiceStatus", required = false) String invoiceStatus,
                              @RequestParam(value = "companyName", required = false) String companyName,
                              @RequestParam(value = "beginTime", required = false) String beginTime,
                              @RequestParam(value = "endTime", required = false) String endTime) {
        SalesInvoiceOrder salesInvoiceOrder = new SalesInvoiceOrder();
        salesInvoiceOrder.setInvoiceStatus(invoiceStatus);
        salesInvoiceOrder.setCompanyName(companyName);
        salesInvoiceOrder.setBeginTime(beginTime);
        salesInvoiceOrder.setEndTime(endTime);
        startPage();
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        salesInvoiceOrder.setDeptId(companyId);
        List<SalesInvoiceOrder> salesInvoiceOrderList = invoiceService.selectSalesInvoice(salesInvoiceOrder);
        return getDataTable(salesInvoiceOrderList);
    }

    /**
     * 新增销售发票
     */
    @GetMapping("/selectInfromation")
    public Map<String, Object> add() {
        Map<String, Object> resMap = new HashMap<>();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long companyId = sysUser.getCompanyId();
        Long deptId = sysUser.getDeptId();
        Long userId = sysUser.getUserId();
        //使用SimpleDateFormat的parse()方法生成Date
        SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
        Date dates = null;
        try {
            dates = a.parse(a.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String invoiceNum = purchaseOrderService.orderNum(dates, 3);
        List<SysUser> sysUsers = userService.selectSalesmanList(companyId);
        //定义一个i，用于采购的业务员的判断
        int i = 0;
        if (!deptId.equals(companyId)) {
            if (sysUsers.size() != 0) {
                for (int i1 = sysUsers.size() - 1; i1 >= 0; i1--) {
                    if (!sysUsers.get(i1).getUserId().equals(userId)) {
                        sysUsers.remove(i1);
                        i++;
                    }
                }
            }
        }
        resMap.put("user", sysUsers);
        resMap.put("i", i);
        resMap.put("salesInvoiceNum", invoiceNum);
        return resMap;
    }

    /**
     * 新增保存销售发票
     */
    //@RequiresPermissions("business:salesInvoice:add")
    @Log(title = "新增销售发票", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestBody SalesInvoiceOrder salesInvoiceOrder) {

//        return null;
        if (salesInvoiceOrder.getSalesInvoiceModelList() == null) {
            return AjaxResult.error("销售发票信息不能为空！请重新设置");
        }
        if (salesInvoiceOrder != null) {
            //使用SimpleDateFormat的parse()方法生成Date
            SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
            Date dates = null;
            // try {
//          //       dates = a.parse(a.format(new Date()));
            //     dates = a.parse(a.format(salesInvoiceOrder.getAuditTime()));
            // } catch (ParseException e) {
            //     e.printStackTrace();
            // }
            String s = purchaseOrderService.orderNum(new Date(), 3);
            salesInvoiceOrder.setSalesInvoiceNum(s);
        }
        // salesInvoiceMapper.insertfp(salesInvoiceOrder);
        return toAjax(invoiceService.insertSalesInvoiceOrder(salesInvoiceOrder));
    }

    /**
     * 新增保存销售发票
     */
    @PostMapping("/editInformation")
    @ResponseBody
    public void editInformation(HttpServletRequest request) {
        String phone = request.getParameter("phone");
        String fname = request.getParameter("fname");
        String remarks = request.getParameter("remarks");
        String shdz = request.getParameter("shdz");
        String salesInvoiceNum = request.getParameter("salesInvoiceNum");
        String companyId = request.getParameter("companyId");
        salesInvoiceMapper.editfp(phone, fname, remarks, shdz, salesInvoiceNum, companyId);
    }

    /**
     * 修改销售发票
     */
    @GetMapping("/selectEdit/{salesInvoiceId}")
    public Map<String, Object> edit(@PathVariable("salesInvoiceId") Long salesInvoiceId) {
        Map<String, Object> resMap = new HashMap<>();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        SalesInvoiceOrder salesInvoiceOrder = invoiceService.selectSalesInvoiceOrderById(salesInvoiceId);
        Long companyId = sysUser.getCompanyId();
        Long deptId = sysUser.getDeptId();
        Long userId = sysUser.getUserId();
        List<SysUser> sysUsers = userService.selectSalesmanList(companyId);
        //定义一个i，用于采购的业务员的判断
        int i = 0;
        if (!deptId.equals(companyId)) {
            if (sysUsers.size() != 0) {
                for (int i1 = sysUsers.size() - 1; i1 >= 0; i1--) {
                    if (!sysUsers.get(i1).getUserId().equals(userId)) {
                        sysUsers.remove(i1);
                        i++;
                    }
                }
            }
        }
        resMap.put("user", sysUsers);
        resMap.put("salesInvoiceOrder", salesInvoiceOrder);

        // 获取上一条临近的ID
        resMap.put("previousId", salesInvoiceService.querypreviousId(salesInvoiceId));
        // 获取下一条临近的ID
        resMap.put("nextId", salesInvoiceService.queryNextId(salesInvoiceId));
        return resMap;
    }

    /**
     * 修改保存销售发票
     */
    @RequiresPermissions("business:salesInvoice:edit")
    @Log(title = "修改销售发票", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestBody SalesInvoiceOrder salesInvoiceOrder) {
        if (salesInvoiceOrder.getSalesInvoiceModelList() == null) {
            return AjaxResult.error("销售发票信息不能为空！请重新设置");
        }
        return toAjax(invoiceService.updateSalesInvoiceOrder(salesInvoiceOrder));
    }

    /**
     * 删除销售发票
     */
    @RequiresPermissions("business:salesInvoice:remove")
    @Log(title = "删除销售发票", businessType = BusinessType.DELETE)
    @GetMapping("/remove/{salesInvoiceId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("salesInvoiceId") Long salesInvoiceId) {
        return toAjax(invoiceService.deleteSalesInvoiceOrderById(salesInvoiceId));
    }

    /**
     * 选择销货单页面
     */
    @GetMapping("/selectSale")
    public Map<String, Object> selectSaleorderget() {
        Map<String, Object> resMap = new HashMap<>();
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        SaleGoodsOrder saleGoodsOrder = new SaleGoodsOrder();
        saleGoodsOrder.setDeptId(companyId);
//        if (!ShiroUtils.getSysUser().getDeptId().equals(ShiroUtils.getSysUser().getCompanyId())) {
//            saleGoodsOrder.setUserId(ShiroUtils.getUserId());
//        }
        List<SaleGoodsOrder> saleGoodsOrders = saleGoodsService.selectSaleGoodsCustObj(companyId);
        resMap.put("deptName", saleGoodsOrders);
        return resMap;
    }

    /**
     * 查看销售发票
     */
    @GetMapping("/look/{salesInvoiceId}")
    @RequiresPermissions("business:salesInvoice:look")
    public String look(@PathVariable("salesInvoiceId") Long salesInvoiceId, ModelMap mmap) {
        SalesInvoiceOrder salesInvoiceOrder = invoiceService.selectSalesInvoiceOrderById(salesInvoiceId);
        for (SalesInvoiceModel salesInvoiceModel : salesInvoiceOrder.getSalesInvoiceModelList()) {
            if (salesInvoiceModel.getAllNum() == 0) {
                salesInvoiceModel.setUnit(salesInvoiceModel.getUnits());
            }
        }
        Long companyId = WXShiroUtils.getSysUser().getCompanyId();
        Long deptId = WXShiroUtils.getSysUser().getDeptId();
        Long userId = WXShiroUtils.getSysUser().getUserId();
        List<SysUser> sysUsers = userService.selectSalesmanList(companyId);
        //定义一个i，用于采购的业务员的判断
        int i = 0;
        if (!deptId.equals(companyId)) {
            if (sysUsers.size() != 0) {
                for (int i1 = sysUsers.size() - 1; i1 >= 0; i1--) {
                    if (!sysUsers.get(i1).getUserId().equals(userId)) {
                        sysUsers.remove(i1);
                        i++;
                    }
                }
            }
        }
        mmap.put("user", sysUsers);
        mmap.put("salesInvoiceOrder", salesInvoiceOrder);
        return prefix + "/look";
    }

    /**
     * 修改销售发票
     */
    @GetMapping("/outorder/{salesInvoiceId}")
    @RequiresPermissions("business:salesInvoice:outorder")
    public String outorder(@PathVariable("salesInvoiceId") Long salesInvoiceId, ModelMap mmap) {
        SalesInvoiceOrder salesInvoiceOrder = invoiceService.selectSalesInvoiceOrderById(salesInvoiceId);
        Long companyId = WXShiroUtils.getSysUser().getCompanyId();
        Long deptId = WXShiroUtils.getSysUser().getDeptId();
        Long userId = WXShiroUtils.getSysUser().getUserId();
        List<SysUser> sysUsers = userService.selectSalesmanList(companyId);
        //定义一个i，用于采购的业务员的判断
        int i = 0;
        if (!deptId.equals(companyId)) {
            if (sysUsers.size() != 0) {
                for (int i1 = sysUsers.size() - 1; i1 >= 0; i1--) {
                    if (!sysUsers.get(i1).getUserId().equals(userId)) {
                        sysUsers.remove(i1);
                        i++;
                    }
                }
            }
        }

        for (SalesInvoiceModel salesInvoiceModel : salesInvoiceOrder.getSalesInvoiceModelList()) {
            if (salesInvoiceModel.getAllNum() == 0) {
                salesInvoiceModel.setUnit(salesInvoiceModel.getUnits());
            }
        }
        mmap.put("user", sysUsers);
        mmap.put("salesInvoiceOrder", salesInvoiceOrder);
        return prefix + "/outorder";
    }

    /**
     * 查询销货单数量用于比较
     */
    @GetMapping("/compareNum")
    @ResponseBody
    public int selectProductProductType(@RequestParam(value = "saleGoodsModelId") Long saleGoodsModelId, @RequestParam(value = "salesInvoiceNo") Long salesInvoiceNo, @RequestParam(value = "num") int num) {
        SaleGoodsModel saleGoodsModel = saleGoodsService.selectSaleGoodsModelByModelId(saleGoodsModelId);
        if (saleGoodsModel.getUnit().equals("盒")) {
            saleGoodsModel.setRemainingNum(saleGoodsModel.getRemainingNum() / saleGoodsModel.getFactor().intValue());
        }
        SalesInvoiceModel salesInvoiceModel = invoiceService.selectSalesInvoiceModelById(salesInvoiceNo);
        int remainingNum = saleGoodsModel.getRemainingNum() + salesInvoiceModel.getNum();
        if (num > remainingNum) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 根据销货单生成 随货单ajax 随货单是把该销货单 所有的都打印
     */
    @Transactional
    @GetMapping("/dataIntowithOrder")
    @ResponseBody
    public JSONObject dataIntoContract(@RequestParam(value = "salesInvoiceId", required = false) Long salesInvoiceId, @RequestParam(value = "rowFalg", required = false) int rowFalg) {
        SalesInvoiceOrder salesInvoiceOrder = invoiceService.selectSalesInvoiceOrderById(salesInvoiceId);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        HashMap hashMap1 = new HashMap();
        hashMap1.put("deptId", sysUser.getCompanyId());
        hashMap1.put("companyId", salesInvoiceOrder.getCompanyId());
        hashMap1.put("gradeStatus", "02");
        //  CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(hashMap1);
        JSONObject jsonObject = new JSONObject();
        //本公司名称
        jsonObject.put("deptNameVal", iSysDeptService.selectDeptById(sysUser.getCompanyId()).getDeptName());
        //单据编号 是销货单的编号
        jsonObject.put("contractNo", salesInvoiceOrder.getSalesInvoiceNum());
        //客户名称
        jsonObject.put("purchaseName", salesInvoiceOrder.getCompanyName());
        //单据日期 contractDate
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        jsonObject.put("contractDate", fmt.format(salesInvoiceOrder.getCreateTime()));

        Long customerId = salesInvoiceOrder.getDeptId();
        Long companyId = salesInvoiceOrder.getCompanyId();
        //客户地址
//        Company company = iCompanyServer.selectByCompanyId(customerId);
//        jsonObject.put("contractAddress", company.getProvince() + company.getCity() + company.getOtherCorporateAddress());
        Company company = iCompanyServer.selectByCompanyId(companyId);
        jsonObject.put("contractAddress", company.getRasProvince() + company.getRasCity() + company.getRasDistrict() + company.getRasAddress());

        //收获地址 warehouseAddress
//        Company mycompany = iCompanyServer.selectByCompanyId(ShiroUtils.getSysUser().getCompanyId());
//        jsonObject.put("warehouseAddress", mycompany.getProvince() + mycompany.getCity() + mycompany.getOtherCorporateAddress());

//        Company mycompany = iCompanyServer.selectByCompanyId(companyId);
//        jsonObject.put("warehouseAddress", mycompany.getProvince() + mycompany.getCity() + mycompany.getOtherCorporateAddress());
        jsonObject.put("warehouseAddress", company.getWarehouseAddress());

        //公司电话
//        jsonObject.put("custPhone", iCompanyInvoiceService.selectByCompanyId(customerId).getCorporateRegisterPhone());
        jsonObject.put("custPhone", company.getCorporateRegisterPhone());

        //销售订单产品
        JSONArray jsonArrayModel = new JSONArray();
        for (int i = 0; i < salesInvoiceOrder.getSalesInvoiceModelList().size() - rowFalg; i++) {
            jsonArrayModel.add(salesInvoiceOrder.getSalesInvoiceModelList().get(i));
        }
        jsonObject.put("models", jsonArrayModel);
        //总数量
        int totalNum = 0;
        for (int i = 0; i < salesInvoiceOrder.getSalesInvoiceModelList().size() - rowFalg; i++) {
            totalNum += salesInvoiceOrder.getSalesInvoiceModelList().get(i).getNum();
        }
        jsonObject.put("totalNum", totalNum);
        //总金额
        BigDecimal totalMoney = new BigDecimal("0.00");
        for (int i = 0; i < salesInvoiceOrder.getSalesInvoiceModelList().size() - rowFalg; i++) {
            totalMoney = totalMoney.add(salesInvoiceOrder.getSalesInvoiceModelList().get(i).getTaxTotal());
        }
        jsonObject.put("totalMoney", totalMoney);
        //制单人
        jsonObject.put("makeOrderName", sysUserMapper.selectUserByNickName(salesInvoiceOrder.getCreateBy()));

        //收货人 companyOther
        //收货人及联系电话
        String str = company.getWarehousePhone();

        String reg = "[^\u4e00-\u9fa5]";
        if (!"".equals(str) && str != null) {
            str = str.replaceAll(reg, "");
        } else {
            str = "";
        }
        jsonObject.put("consignee", str);

        //出库单说明信息
        JSONArray jsonContractTerms = new JSONArray();
        Company company1 = iCompanyServer.selectByCompanyId(sysUser.getCompanyId());
        String contractTerms = company1.getOutboundDeliveryMemo();
        if (contractTerms == null || "".equals(contractTerms)) {
            jsonObject.put("code", 500);
            jsonObject.put("message", "您的出库单说明信息为空,请先在个人信息-我的公司档案完善出库单说明信息。");
            throw new RuntimeException("您的出库单说明信息为空,请先在个人信息-我的公司档案完善出库单说明信息。");
        }
        if (contractTerms != null) {
            //根据回车进行分割
            String[] contractTermsArr = contractTerms.split("\\r?\\n");
            for (int i = 0; i < contractTermsArr.length; i++) {
                //每行108个字符
                String[] strings = Util.stringToArray(contractTermsArr[i]);
                String interception = Util.interception(strings, 108);
                //根据回车进行分割
                String[] split = interception.split("换行aaaaa");
                for (int j = 0; j < split.length; j++) {
                    String s = split[j];
                    //第一行的时候拼接上 “说明：”
                    jsonContractTerms.add(s);
                }
            }
            jsonObject.put("contractTerms", jsonContractTerms);
        } else {
            jsonObject.put("contractTerms", "");
        }
        return jsonObject;
    }

    /**
     * 随货单 剩余的数据
     * tableData 前端 展示的 数据的modelid集合
     */
    @PostMapping("/dataIntowithOrderOtherData")
    @ResponseBody
    public JSONObject dataIntowithOrderOtherData(String[] tableData, Long salesInvoiceId) {
        //每一页封装为一哥JSONObject
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        //处理数据 传过来的以，分割的字符串
        //每条数据查询出从表主键id 放到集合中
        ArrayList<Long> tableDataId = new ArrayList();
        for (int i = 0; i < tableData.length; i++) {
            tableDataId.add(Long.parseLong(tableData[i]));
        }
        //根据销货单id查询 销货单从表
        List<SalesInvoiceModel> salesInvoiceModels = invoiceService.selectSalesInvoiceModelByOrderId(salesInvoiceId);

        //新建对比数组，用于判断执行什么操作
        ArrayList<Long> arrayList = new ArrayList();
        for (SalesInvoiceModel model : salesInvoiceModels) {
            arrayList.add(model.getSalesInvoiceNo());
        }
        //数组中剩余的数就是需要删除的数据
        for (Long o1 : tableDataId) {
            Iterator<Long> iterator = arrayList.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().equals(o1)) {
                    iterator.remove();
                }
            }
        }

        //剩下的则是 要重新生成的 随货单
        //分为几页arrayList.size()/tableData.length+1
        jsonObject.put("page", (int) Math.ceil((double) arrayList.size() / tableData.length));
        //如果剩余的只有一页了
        if (arrayList.size() <= tableData.length) {
            //总数量
            int totalNuma = 0;
            //总金额
            BigDecimal totalMoneya = new BigDecimal("0.00");
            JSONArray jsonArrayModel = new JSONArray();
            for (int j = 0; j < arrayList.size(); j++) {
                //销售订单产品
                SalesInvoiceModel salesInvoiceModel = invoiceService.selectSalesInvoiceModelById(arrayList.get(j));
                jsonArrayModel.add(salesInvoiceModel);
                totalNuma += salesInvoiceModel.getNum();
                totalMoneya = totalMoneya.add(salesInvoiceModel.getTaxAmount());
            }
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("models", jsonArrayModel);
            jsonObject1.put("totalNum", totalNuma);
            jsonObject1.put("totalMoney", totalMoneya);
            jsonArray.add(jsonObject1);
        } else {
            //这里则是 剩余的超过一页
            //外层for循环控制 第几页
            for (int i = 0; i < (int) Math.ceil((double) arrayList.size() / tableData.length); i++) {
                //当页总数量
                int totalNum = 0;
                //当页总金额
                BigDecimal totalMoney = new BigDecimal("0.00");
                //取最后一页的条数 取模
                int lastRow = arrayList.size() % tableData.length;
                //不是最后一页的话
                //存放modelmodel数据
                JSONArray jsonArrayModel1 = new JSONArray();
                if (i != ((int) Math.ceil((double) arrayList.size() / tableData.length)) - 1) {

                    for (int j = i * tableData.length; j < tableData.length + i * tableData.length; j++) {

                        SalesInvoiceModel salesInvoiceModel = invoiceService.selectSalesInvoiceModelById(arrayList.get(j));
                        jsonArrayModel1.add(salesInvoiceModel);
                        totalNum += salesInvoiceModel.getNum();
                        totalMoney = totalMoney.add(salesInvoiceModel.getTaxAmount());
                    }
                } else {
                    //是最后一页的话
                    for (int j = arrayList.size() - lastRow; j < arrayList.size(); j++) {
                        //销售订单产品
                        SalesInvoiceModel salesInvoiceModel = invoiceService.selectSalesInvoiceModelById(arrayList.get(j));
                        jsonArrayModel1.add(salesInvoiceModel);
                        totalNum += salesInvoiceModel.getNum();
                        totalMoney = totalMoney.add(salesInvoiceModel.getTaxAmount());
                    }
                }
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("models", jsonArrayModel1);
                jsonObject1.put("totalNum", totalNum);
                jsonObject1.put("totalMoney", totalMoney);
                //jsonObject.put("page" + i, jsonObject1);
                jsonArray.add(jsonObject1);
            }

        }
        jsonObject.put("lastRow", tableData.length);
        jsonObject.put("row", jsonArray);
        return jsonObject;
    }

    /**
     * 查询供应商的绑定业务员
     */
    @PostMapping("/selectUser/{companyId}")
    @ResponseBody
    public AjaxResult selectUser(@PathVariable("companyId") Long companyId) {
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        map.put("companyId", companyId);
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
        if (companyOther != null) {
            return AjaxResult.success(companyOther);
        } else {
            return AjaxResult.error("该公司没有合作单位请设置负责人信息");
        }
    }

}
